<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Pay{
    
    private $user_account;		//会员信息
    private $MoenyCount; 	//商品总金额 
    private $shops; 		//商品信息
    private $pay_type;		//支付类型
    private $operator_type;	//付款类型 买商品 充值
    private $dingdan_query = true;	//订单的	mysql_qurey 结果
    public $scookie = null;
    public $alipay_config;//支付宝配置
    
    
    function __construct()
    {
        $this->ci =& get_instance();
        $this->alipay_config = $this->ci->web_config['ALIPAY'];
    }
    /**
     * 
     * @param type $user_id 用户user_id
     * @param type $pay_type 付款方式
     * @param type $operator_type 操作类型
     */
    public function init($user_id,$pay_type,$operator_type){
        //开启事务
        $this->ci->db->trans_begin();
        //获取用户信息
        $this->user_account = $this->ci->db->query("select * from tan_bbs_account where user_id = $user_id for update")->row_array();
        $this->pay_type = $pay_type;
        $this->operator_type = $operator_type;
        if($operator_type=='go_record'){
            return $this->go_record();
        }
        return false;
    }
    
    //夺宝商品
    private function go_record(){
        if(is_array($this->scookie)){
            $Cartlist = $this->scookie;
        }else{
            $Cartlist=json_decode(stripslashes(_getcookie("CartShop")),true);
        }
        $shopid = 0;
        $cartData = array();
        foreach ($Cartlist as $key=>$val){
            if(is_array($val)){
                $shopid = $key;
                $cartData = $val;
            }
        }
        if($shopid){
            $shoplist = $this->ci->db->query("SELECT * FROM `tan_go_shoplist` where `id` = $shopid and `q_uid` is null for update")->row_array();
        }
        if(!$shoplist){
            $this->ci->db->trans_rollback();
            return "非法参数";
        }
        $MoenyCount= 0;
        if(count($shoplist)>=1){
            $scookies_arr = array();
            $scookies_arr['MoenyCount'] = 0;
            
            
                if($shoplist['shenyurenshu'] != 0){	
                    
                    $shoplist['cart_gorenci']=$cartData['num'] ? $cartData['num'] : 1;
                    
                    if($shoplist['cart_gorenci'] >= $shoplist['shenyurenshu']){
                        $shoplist['cart_gorenci'] = $shoplist['shenyurenshu'];
                    }
                    $MoenyCount = $shoplist['yunjiage']*$shoplist['cart_gorenci'];
                    $shoplist['cart_xiaoji'] = $shoplist['yunjiage'] * $shoplist['cart_gorenci'];	
                    $shoplist['cart_shenyu'] = $shoplist['zongrenshu']-$shoplist['canyurenshu'];					
                    $scookies_arr[$shopid]['shenyu'] = $shoplist['cart_shenyu'];
                    $scookies_arr[$shopid]['num'] = $shoplist['cart_gorenci'];
                    $scookies_arr[$shopid]['money'] = intval($shoplist['yunjiage']);
                    $scookies_arr['MoenyCount'] = intval($shoplist['cart_xiaoji']);
                }else{
                    $shoplist = array();
                }	
                
                
                
            if(count($shoplist) < 1){			
                $scookies_arr = '0';
                $this->ci->db->trans_rollback();
                return '手速太慢了，商品已经抢光啦!';
            }
        }else{
            $scookies_arr = '0';
            $this->ci->db->trans_rollback();
            return '手速太慢了，商品已经抢光啦!';
        }
        
        $this->MoenyCount = $MoenyCount;
        $this->shoplist = $shoplist;		
        $this->scookies_arr = $scookies_arr;	
        return 'ok';	
    }
    /**
    *	开始支付
    **/
    public function go_pay($pay_checkbox){
        //判断余额是否够
        if($this->user_account['balance'] >= $this->MoenyCount){	
            $user_id=$this->user_account['user_id'];		
            $pay_1 =  $this->pay_bag();				
            if(!$pay_1){return $pay_1;}
            return $pay_1;			
        }
        
        if($this->pay_type == ""){
            return 'not_pay';
        }
        if(is_array($this->scookies_arr)){
            $scookie = serialize($this->scookies_arr);
        }else{
            $scookie= '0';
        }
        if($pay_checkbox){			
            $money = $this->MoenyCount - $this->user_account['balance'];	
            return $this->addmoney_record($money,$scookie);
        }else{
            //全额支付
            return $this->addmoney_record($this->MoenyCount,$scookie);			
        }
        exit;
    }
    
    /* 充值 data 其他数据 */ 
    private function addmoney_record($money=null,$data=null){		
        $uid = $this->user_account['user_id'];
        $dingdancode = pay_get_dingdan_code('C');//订单号
        
        if($this->pay_type == ""){
                return 'not_pay';
        }
        $pay_type = $this->pay_type;
        $time = time();
        if(!empty($data)){
                $scookies = $data;
        }else{
                $scookies = '0';
        }
        $score = 0;
        $product_num = intval($money);
        $product_name = $product_num."个溜珠";
        $create_time = time();
        $query = $this->ci->db->query("INSERT INTO `tan_go_member_addmoney_record` (`uid`, `code`, `money`, `pay_type`, `status`,`time`,`score`,`scookies`) VALUES ('$uid', '$dingdancode', '$money', '$pay_type','未付款', '$time','$score','$scookies')");				
        $query1 = $this->ci->db->query("INSERT INTO `tan_bbs_recharge_order` (`order_nid`,`user_id`,`product_name`,`product_money`,`product_num`,`status`,`type`,`recharge_type`,`create_time`) VALUES ('$dingdancode', '$uid','$product_name', '$money','$product_num','0', '2', 'alipay','$create_time')");				
        if($query && $query1){
            $this->ci->db->query("INSERT INTO `tan_bbs_recharge_list` (`order_nid`,`user_id`,`product_name`,`product_money`,`product_num`,`status`,`type`,`recharge_type`,`create_time`) VALUES ('$dingdancode', '$uid','$product_name', '$money','$product_num','0', '2', 'alipay','$create_time')");
            $this->ci->db->trans_commit();
        }else{
            $this->ci->db->trans_rollback();
            return false;
        }
        
        if($pay_type == "alipay"){
            $this->ci->load->library('Alipay');
            echo "正在跳转支付页面...";
            //构造请求参数
            $args = array();
            $args['number'] = $dingdancode;
            $args['name'] = $product_name;
            $args['total'] = $money;
            $args['content'] = "";
            $args['notify_url'] =  web_url("lottery/notify");
            $args['return_url'] = web_url("lottery_alipay_return");
            $alipay = new Alipay();
            $alipay->recharge($this->alipay_config, $args);exit;
        }
        return true;
    }
    
    
    //账户余额支付
    private function pay_bag(){
        
        $time=time();
        $user_id = $this->user_account['user_id'];
        
        $query_1 = $this->set_dingdan('账户','A');
        /*会员购买过账户剩余金额*/
        $Money = $this->user_account['balance'] - $this->MoenyCount;//账户余额
        $Expend = $this->user_account['expend'] + $this->MoenyCount;//账户总支出
        $pay_zhifu_name = '账户';
        
        //更新用户账户金额
        $query_2 = $this->ci->db->query("UPDATE `tan_bbs_account` SET `balance`= $Money,`expend`=$Expend,`is_lottery`=1 WHERE (`user_id` = $user_id)");//金额
        
        $query_3 = $info = $this->ci->db->query("select * from tan_bbs_account where  user_id = ".$user_id)->row_array();
        $query_4 = $this->ci->db->query("INSERT INTO `tan_go_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$user_id', '-1', '$pay_zhifu_name', '购买了商品', '{$this->MoenyCount}', '$time')");	
        $query_5 = true;
        $query_insert = true;
        
        $goods_count_num = 0;
        //如果当前参与人数已经超过总人数，并且该商品的最大期数已经到达了
        if($this->shoplist['canyurenshu'] >= $this->shoplist['zongrenshu'] && $this->shoplist['maxqishu'] >= $this->shoplist['qishu']){
            //更新参与人数和剩余人数
            $this->ci->db->query("UPDATE `tan_go_shoplist` SET `canyurenshu`=`zongrenshu`,`shenyurenshu` = '0' where `id` = ".$this->shoplist['id']);
        }else{	
            //计算剩余人数
            $shenyurenshu = $this->shoplist['zongrenshu'] - $this->shoplist['canyurenshu'];			
            $query = $this->ci->db->query("UPDATE `tan_go_shoplist` SET `canyurenshu` = ".$this->shoplist['canyurenshu'].",`shenyurenshu` = '$shenyurenshu' WHERE `id`= ".$this->shoplist['id']);	
            if(!$query)$query_5=false;
        }
        $goods_count_num = $this->shoplist['goods_count_num'];//购买数量
        
        //添加用户经验
        
        //更新社区用户溜珠明细
        $this->ci->db->insert("bbs_zhu_detail",array("user_id"=>$user_id,"num"=>intval($goods_count_num),"type"=>"溜溜夺宝","style"=>2,"create_time"=>time()));
        $insert_detail = $this->ci->db->insert_id();
        $dingdancode = $this->dingdancode;//订单编码
        //更新云购状态
        $query_6 = $this->ci->db->query("UPDATE `tan_go_member_go_record` SET `status`='已付款,未发货,未完成' WHERE `code`='$dingdancode' and `uid` = '$user_id'");		
        $query_7 = $this->dingdan_query;	
        //更新总的云购数量
        $query_8 = $this->ci->db->query("UPDATE `tan_go_caches` SET `value`=`value` + $goods_count_num WHERE `key`='goods_count_num'");
        $this->goods_count_num = $goods_count_num;

        if($query_1 && $query_2 && $query_3 && $query_4 && $query_5 && $insert_detail && $query_6 && $query_7 && $query_insert && $query_8){
            
            if($info['balance'] == $Money){	
                $this->ci->db->trans_complete();					
                if($this->shoplist['canyurenshu'] >= $this->shoplist['zongrenshu'] && $this->shoplist['maxqishu'] >= $this->shoplist['qishu']){
                    
                    $this->ci->db->trans_begin();
                    //新增下一期云购商品
                    $query_insert = $this->pay_insert_shop($this->shoplist,'add');
                    if(!$query_insert){
                        $this->ci->db->trans_rollback();								
                    }else{
                        $this->ci->db->trans_complete();						
                    }
                    $this->ci->db->query("UPDATE `tan_go_shoplist` SET `canyurenshu`=`zongrenshu`,`shenyurenshu` = '0' where `id` = ".$this->shoplist['id']);
                }
                return true;
            }else{
                $this->ci->db->trans_rollback();
                return false;
            }
        }else{
            $this->ci->db->trans_rollback();
            return false;
        }
    }
    
    /*生成订单*/
    private function set_dingdan($pay_type='',$dingdanzhui=''){
        $user_id = $this->user_account['user_id'];
        $uphoto = "";
        $username = "";	
        $insert_html='';					
        $this->dingdancode = $dingdancode= pay_get_dingdan_code($dingdanzhui);		//订单号			
        
        $dingdancode_tmp = 0;	//单独商品订单
        $ip =  $this->ci->input->ip_address();

        //订单时间
        $time = sprintf("%.3f",microtime(true));
        $this->MoenyCount=0;
        $ret_data = array();
        //获取用户所需数量的云购码
        $this->pay_get_shop_codes($this->shoplist['cart_gorenci'],$this->shoplist,$ret_data);
        
        $this->dingdan_query = $ret_data['query'];
        
        if(!$ret_data['query']) $this->dingdan_query = false;
        $codes = $ret_data['user_code'];//得到的云购码		
        $codes_len = intval($ret_data['user_code_len']);//得到云购码个数	
        $money = $codes_len * $this->shoplist['yunjiage'];//单条商品的总价格
        
        $this->MoenyCount = $money;//总价格				
        $status='未付款,未发货,未完成';					
        $this->shoplist['canyurenshu'] = intval($this->shoplist['canyurenshu']) + $codes_len;//增加参与人数
        $this->shoplist['goods_count_num'] = $codes_len;
        $this->shoplist['title'] = addslashes($this->shoplist['title']);
        
        if($codes_len){
            $insert_html.="('$dingdancode','$dingdancode_tmp','$user_id','$username','$uphoto','".$this->shoplist['id']."','".$this->shoplist['title']."','".$this->shoplist['qishu']."','$codes_len','$money','$codes','$pay_type','$ip','$status','$time'),";		
        }
        
        
        $sql="INSERT INTO `tan_go_member_go_record` (`code`,`code_tmp`,`uid`,`username`,`uphoto`,`shopid`,`shopname`,`shopqishu`,`gonumber`,`moneycount`,`goucode`,`pay_type`,`ip`,`status`,`time`) VALUES ";
        $sql .= trim($insert_html,',');				
        return $this->ci->db->query($sql);
    }
    
    
    /*
    *   生成购买的云购码
    *	user_num 		@生成个数
    *	shopinfo		@商品信息
    *	ret_data		@返回信息
    */
    private function pay_get_shop_codes($user_num=1,$shopinfo=null,&$ret_data=null){
        
        $ret_data['query'] = true;
        //搜索云购码仓库
        $table = 'tan_go_'.$shopinfo['codes_table'];
        $codes_arr = array();
        //查找最大的云购码仓库，然后从里面取出指定数量的云购码
        $codes_one = $this->ci->db->query("select id,s_id,s_cid,s_len,s_codes from `$table` where `s_id` = '".$shopinfo["id"]."' order by `s_cid` DESC  LIMIT 1 for update")->row_array();
        
        $codes_arr[$codes_one['s_cid']] = $codes_one;	
        
        $codes_count_len = $codes_arr[$codes_one['s_cid']]['s_len'];
        //如果当前所需数量超过库存数量，那么从下一序列号较小的表里取出
        if($codes_count_len < $user_num && $codes_one['s_cid'] > 1){	
            for($i=$codes_one['s_cid']-1;$i>=1;$i--):
                $codes_arr[$i] = $this->ci->db->query("select id,s_id,s_cid,s_len,s_codes from `$table` where `s_id` = '".$shopinfo['id']."' and `s_cid` = '$i'  LIMIT 1 for update")->row_array();
                $codes_count_len += $codes_arr[$i]['s_len'];	
                //当取出的数量大于所需数量后，停止取出
                if($codes_count_len > $user_num)  break;
            endfor;
        }
        //如果剩余的全部云码不满足用户所需的数量，那么就将剩余的全部给用户
        if($codes_count_len < $user_num) $user_num = $codes_count_len;

        $ret_data['user_code'] = '';
        $ret_data['user_code_len'] = 0;
        
        foreach($codes_arr as $icodes){	
            //用户所需数量
            $u_num = $user_num;	//$user_num = 1	
            $icodes['s_codes'] = unserialize($icodes['s_codes']);//将云购码转化为数组
            $code_tmp_arr = array_slice($icodes['s_codes'],0,$u_num);//将数组中截取长度为$u_num的一段数据,如果总长度小于所需长度，则全部取出
            $ret_data['user_code'] .= implode(',',$code_tmp_arr);//将数组转化为字符串
            $code_tmp_arr_len = count($code_tmp_arr);//获取取出来的数据长度
            //如果取出来的数量小于用户所需数量
            if($code_tmp_arr_len < $u_num){
                    $ret_data['user_code'] .= ',';//继续拼接云购码
            }
            //取出后剩余的云购码，如果全部取出完了，那么此时为array()空数组
            $icodes['s_codes'] = array_slice($icodes['s_codes'],$u_num,count($icodes['s_codes']));
            $icode_sub = count($icodes['s_codes']);//计算仓库中剩余的数量		
            $icodes['s_codes'] = serialize($icodes['s_codes']);//将剩余的云购码序列化
            
            if(!$icode_sub){//如果当前仓库内的云购码取完了
                $this->ci->db->where(array("id"=>$icodes["id"]))->update($table,array("s_cid"=>0,"s_codes"=>$icodes['s_codes'],"s_len"=>$icode_sub));
                $query = $this->ci->db->affected_rows();
                if(!$query)$ret_data['query'] = false;
            }else{//更新剩余后的仓库数量		
                $this->ci->db->where(array("id"=>$icodes["id"]))->update($table,array("s_codes"=>$icodes['s_codes'],"s_len"=>$icode_sub));
                $query = $this->ci->db->affected_rows();
                if(!$query)$ret_data['query'] = false;
            }
            $ret_data['user_code_len'] += $code_tmp_arr_len;
            $user_num  = $user_num - $code_tmp_arr_len;
        }
    }
    
    /*
        揭晓与插入商品
        @shop   商品数据
    */
    private function pay_insert_shop($shop='',$type=''){
        
        $time=sprintf("%.3f",microtime(true)+180);//获奖揭晓时间
        $this->ci->load->library('Tocode');
        $tocode = new Tocode($this->ci->db);
        $tocode->shop = $shop;	
        //揭晓奖励
        $tocode->run_tocode($time,100,$shop['canyurenshu'],$shop);
        //中奖码
        $code =$tocode->go_code;
        //中奖码计算所需记录信息
        $content = addslashes($tocode->go_content);
        //时间计算总和
        $counttime = $tocode->count_time;	
        //中奖者记录
        $u_go_info = $this->ci->db->query("select * from `tan_go_member_go_record` where `shopid` = ".$shop['id']." and `shopqishu` = ".$shop['qishu']." and `goucode` LIKE  '%$code%'")->row_array();	
        //中奖人信息
        $u_info = $this->ci->db->query("select tan_users.user_id uid,tan_users.username,tan_users.email,tan_users.mobile,tan_users_info.head_img,tan_users_info.nickname from `tan_users` left join tan_users_info on tan_users_info.user_id = tan_users.user_id where tan_users.user_id = ".$u_go_info["uid"])->row_array();	
        
        //更新商品
        $query = true;
        if($u_info){		
            $u_info['username'] = _htmtocode($u_info['username']);
            $q_user = serialize($u_info);
            $gtimes = 180;
            if($gtimes == 0 || $gtimes == 1){
                $q_showtime = 'N';
            }else{
                $q_showtime = 'Y';
            }
            $sqlss = "UPDATE `tan_go_shoplist` SET 
                            `canyurenshu`=`zongrenshu`,
                            `shenyurenshu` = '0',
                            `q_uid` = '$u_info[uid]',
                            `q_user` = '$q_user',
                            `q_user_code` = '$code',
                            `q_content`	= '$content',
                            `q_counttime` ='$counttime',
                            `q_end_time` = '$time',
                            `q_showtime` = '$q_showtime',
                            `end_time` = ".time()."
                             where `id` = '$shop[id]'";

            $q = $this->ci->db->query($sqlss);

            if(!$q)$query = false;	

            if($q){
                    $q = $this->ci->db->query("UPDATE `tan_go_member_go_record` SET `huode` = '$code' where `id` = '$u_go_info[id]' and `code` = '$u_go_info[code]' and `uid` = '$u_go_info[uid]' and `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]'");
                    if(!$q) {
                            $query = false;
                    }else{
                        //TODO中奖发送手机短信、邮箱短信提醒
//                        $post_arr= array("uid"=>$u_info['uid'],"gid"=>$shop['id'],"send"=>1);
//                        _g_triggerRequest(WEB_PATH.'/api/send/send_shop_code',false,$post_arr);
                    }
            }else{
                    $query =  false;
            }
        }else{	
                $query =  false;
        }

        /******************************/


        /*增加新一期夺宝商品*/
        if($query){
            if($shop['qishu'] < $shop['maxqishu']){		
                $maxinfo = $this->ci->db->query("select * from `tan_go_shoplist` where `sid` = '$shop[sid]' order by `qishu` DESC LIMIT 1")->row_array();
                if(!$maxinfo){
                    $maxinfo=array("qishu"=>$shop['qishu']);
                }			
                $intall = $this->content_add_shop_install($maxinfo,false);		
                if(!$intall) return $query;
            }
        }
        return $query;
    }
    
    /*
    新建一期商品
    info 	 商品的ID 或者 商品的数组
    使用此函数注意传进来的的商品期数不等于最大期数
    autocommit @是否开启事物
   */
    private function content_add_shop_install($info=null,$autocommit=true){

        if($autocommit){
                $this->ci->db->trans_begin();
        }

        unset($info['id']);
        unset($info['q_uid']);
        unset($info['q_user']);
        unset($info['q_user_code']);
        unset($info['q_content']);
        unset($info['q_counttime']);
        unset($info['q_end_time']);		


        $info['xsjx_time']=0;
        $info['time'] = time();
        $info['qishu'] = intval($info['qishu']);
        $info['qishu']++;
        $info['canyurenshu'] = '0';
        $info['shenyurenshu'] = $info['zongrenshu'];
        $info['codes_table'] = $this->content_get_codes_table();
        $info['q_showtime']= 'N';
        $info['title'] = _htmtocode($info['title']);
        $info['title2'] = _htmtocode($info['title2']);

        $keys  = $vals = '(';
        foreach($info as $key=>$val){
                $keys.="`$key`,";
                $vals.="'$val',";
        }
        $keys = rtrim($keys,',');
        $vals = rtrim($vals,',');
        $keys.= ')';
        $vals.= ')';

        $sql = "INSERT INTO `tan_go_shoplist` ".$keys." VALUES ".$vals;
        $q1 = $this->ci->db->query($sql);
        $id = $this->ci->db->insert_id();	
        $q2 = $this->content_get_go_codes($info['zongrenshu'],3000,$id);

        if($autocommit){
                if($q1 && $q2){
                        $this->ci->db->trans_commit();
                        return true;
                }else{
                        $this->ci->db->trans_rollback();
                        return false;
                }			
        }else{
                if($q1 && $q2){			
                        return true;
                }else{		
                        return false;
                }
        }

   }
   
   /*
	判断云购码表的状态
    */
    private function content_get_codes_table(){
        $num = $this->ci->db->query("SELECT * from `tan_go_caches` where `key` = 'shopcodes_table' LIMIT 1")->row_array();//获取云购表名称
        $table = 'tan_go_shopcodes_'.$num['value'];	
        $shopcodes_table = $this->ci->db->query("SHOW TABLE STATUS LIKE '$table'")->row_array();//判断表的状态

        if(!$shopcodes_table || !$num) return false;//不存在云购码表仓库
        if($shopcodes_table['Auto_increment'] >=99999){//如果云购码表里的数量超出了99999，那么重新创建
            $num = intval($num['value'])+1;
            $shopcodes_table = 'shopcodes_'.$num;//创建表名
            $q1 = $this->ci->db->query("		
                            CREATE TABLE `tan_go_$shopcodes_table` (
                              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                              `s_id` int(10) unsigned NOT NULL COMMENT '商品id',
                              `s_cid` smallint(5) unsigned NOT NULL,
                              `s_len` smallint(5) DEFAULT NULL COMMENT '商品云购码的长度',
                              `s_codes` text COMMENT '商品云购码',
                              `s_codes_tmp` text COMMENT '商品云购码',
                              PRIMARY KEY (`id`),
                              KEY `s_id` (`s_id`),
                              KEY `s_cid` (`s_cid`),
                              KEY `s_len` (`s_len`)
                            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
            ");
            $q2 = $this->ci->db->query("UPDATE `@#_caches` SET `value` = '$num' where `key` = 'shopcodes_table'");
            if(!$q1 || !$q2)return false;
        }else{
                $num = intval($num['value']);
                $shopcodes_table = 'shopcodes_'.$num;
        }
        return $shopcodes_table;//返回云购码表名

    }
    
    /*
   生成云购码 
   CountNum @ 生成个数
   len 	    @ 生成长度
   sid	    @ 商品ID
    */
    private function content_get_go_codes($CountNum=null,$len=null,$sid=null){	
        $table = $this->ci->db->query("SELECT * from `tan_go_caches` where `key` = 'shopcodes_table' LIMIT 1")->row_array();
        $table = 'tan_go_shopcodes_'.$table['value'];

        $num = ceil($CountNum/$len);//每个云购码表里最多存放3000个云购码
        $code_i = $CountNum;
        if($num == 1){
            $codes=array();
            for($i=1;$i<=$CountNum;$i++){
                    $codes[$i]=10000000+$i;
            }
            shuffle($codes);//函数把数组中的元素按随机顺序重新排列。 
            $codes=serialize($codes);//序列化云购码
            $query = $this->ci->db->query("INSERT INTO `$table` (`s_id`, `s_cid`, `s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '1','$CountNum','$codes','$codes')");
            unset($codes);
            return $query;
        }
        $query_1 = true;
        for($k=1;$k<$num;$k++){
            $codes=array();
            for($i=1;$i<=$len;$i++){
                    $codes[$i]=10000000+$code_i;
                    $code_i--;
            }
            shuffle($codes);
            $codes=serialize($codes);
            $query_1 = $this->ci->db->query("INSERT INTO `$table` (`s_id`, `s_cid`, `s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '$k','$len','$codes','$codes')");
            unset($codes);
        }
        $CountNum = $CountNum - (($num-1)*$len);
        $codes=array();	
        for($i=1;$i<=$CountNum;$i++){
            $codes[$i]=10000000+$code_i;	
            $code_i--;
        }
        shuffle($codes);
        $codes=serialize($codes);
        $query_2 = $this->ci->db->query("INSERT INTO `$table` (`s_id`, `s_cid`,`s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '$num','$CountNum','$codes','$codes')");
        unset($codes);
        return $query_1 && $query_2;
    }
}